import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_shop/cons/global_cons.dart';
import 'package:flutter_shop/pages/base/base_presenter.dart';
import 'package:flutter_shop/pages/base/base_state.dart';
import 'package:flutter_shop/pages/common/common_router.dart';
import 'package:flutter_shop/pages/common/login/entity/base_info.dart';
import 'package:flutter_shop/r.dart';
import 'package:flutter_shop/res/colors.dart';
import 'package:flutter_shop/res/styles.dart';
import 'package:flutter_shop/routers/navigator_utils.dart';
import 'package:flutter_shop/utils/sp_util.dart';
import 'package:flutter_shop/utils/utils.dart';
import 'package:flutter_shop/widget/custom_dialog.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:permission_handler/permission_handler.dart';

///Title:闪屏页面 <br/>
///Description: <br/>
///author:xiemiao <br/>
///date: 2020-02-21 <br/>
///version 1.0 <br/>
class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends BaseState<SplashPage, BasePresenter> {
  ///引导图片
  final List<String> _guidePics = [
    R.assetsImgAppGuide01,
    R.assetsImgAppGuide02,
    R.assetsImgAppGuide03,
    R.assetsImgAppGuide04,
  ];

  ///状态 [0:展示splash 1:展示引导]
  int _status = 0;

  @override
  void buildComplete() async {
    //初始化sp
    await SpUtil.getInstance();
    //第一次进入
    if (SpUtil.getBool(GlobalCons.KEY_FIRST_ENTRY, defValue: true)) {
      /// 预先缓存图片，避免直接使用时因为首次加载造成闪动
      _guidePics.forEach((image) {
        precacheImage(AssetImage(image), context);
      });
    }

    //恢复用户信息
    BaseInfo.restoreUserInfo(context);

    //请求权限
    _requestPermission();
  }

  ///请求权限
  void _requestPermission() async {
    //请求权限
    Map<PermissionGroup, PermissionStatus> permissions = await PermissionHandler().requestPermissions([
      PermissionGroup.contacts,
      PermissionGroup.storage,
      PermissionGroup.location,
      PermissionGroup.camera,
    ]);

    //校验权限
    PermissionStatus contactsPermStatus = await PermissionHandler().checkPermissionStatus(PermissionGroup.contacts);
    PermissionStatus storagePermStatus = await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
    PermissionStatus locationPermStatus = await PermissionHandler().checkPermissionStatus(PermissionGroup.location);
    PermissionStatus cameraPermStatus = await PermissionHandler().checkPermissionStatus(PermissionGroup.camera);

    if (contactsPermStatus == PermissionStatus.granted &&
        storagePermStatus == PermissionStatus.granted &&
        locationPermStatus == PermissionStatus.granted &&
        cameraPermStatus == PermissionStatus.granted) {
      ///权限都申请成功初始化闪屏
      _initSplash();
    } else if (contactsPermStatus == PermissionStatus.denied ||
        storagePermStatus == PermissionStatus.denied ||
        locationPermStatus == PermissionStatus.denied ||
        cameraPermStatus == PermissionStatus.denied) {
      ///有任何一组权限被用户拒绝
      //拼接提示权限文本
      StringBuffer sb = new StringBuffer();
      sb.write(contactsPermStatus == PermissionStatus.denied ? "联系人," : "");
      sb.write(storagePermStatus == PermissionStatus.denied ? "存储," : "");
      sb.write(locationPermStatus == PermissionStatus.denied ? "定位," : "");
      sb.write(cameraPermStatus == PermissionStatus.denied ? "相机," : "");
      String tip = Utils.removePostfix(sb.toString(), ",");

      Utils.showCustomDialog(
          context,
          ConfirmDialog(
            "您拒绝了应用的必要权限:\n[$tip],是否重新申请?",
            canBackDismiss: false,
            confirmCallback: () => _requestPermission(),
            cancelCallback: () => SystemNavigator.pop(),
          ));
    } else if (contactsPermStatus == PermissionStatus.neverAskAgain ||
        storagePermStatus == PermissionStatus.neverAskAgain ||
        locationPermStatus == PermissionStatus.neverAskAgain ||
        cameraPermStatus == PermissionStatus.neverAskAgain) {
      ///有任何一组权限选了不再提示
      //拼接提示权限文本
      StringBuffer sb = new StringBuffer();
      sb.write(contactsPermStatus == PermissionStatus.neverAskAgain ? "联系人," : "");
      sb.write(storagePermStatus == PermissionStatus.neverAskAgain ? "存储," : "");
      sb.write(locationPermStatus == PermissionStatus.neverAskAgain ? "定位," : "");
      sb.write(cameraPermStatus == PermissionStatus.neverAskAgain ? "相机," : "");
      String tip = Utils.removePostfix(sb.toString(), ",");

      Utils.showCustomDialog(
          context,
          ConfirmDialog(
            "您禁用了应用的必要权限:\n[$tip],请到设置里允许?",
            canBackDismiss: false,
            confirmText: "去设置",
            confirmCallback: () async {
              await PermissionHandler().openAppSettings();
              SystemNavigator.pop();
            },
            cancelCallback: () => SystemNavigator.pop(),
          ));
    }
  }

  void _initSplash() {
    //1500毫秒后,引导或进入首页
    Utils.postDelayed(1500, () {
      if (SpUtil.getBool(GlobalCons.KEY_FIRST_ENTRY, defValue: true)) {
        SpUtil.putBool(GlobalCons.KEY_FIRST_ENTRY, false);
        //显示引导页面
        setState(() {
          _status = 1;
        });
      } else {
        //跳转index_page
        _goHome();
      }
    });
  }

  void _goHome() {
    NavigatorUtils.push(context, CommonRouter.indexPage, replace: true);
  }

  @override
  Widget build(BuildContext context) {
    //屏幕适配
    ScreenUtil.init(context, width: 750, height: 1334);

    return Material(
      color: Colors.white,
      child: _status == 0 ? _splash() : _guide(),
    );
  }

  Widget _splash() {
    return Container(
      padding: EdgeInsets.only(bottom: 30),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          Image.asset(R.assetsImgLogo),
          Gaps.v_gap_10,
          Text("百姓量贩+", style: TextStyles.common_text),
        ],
      ),
    );
  }

  int _currentIndex;

  Widget _guide() {
    return Container(
      child: Stack(
        alignment: AlignmentDirectional.bottomCenter,
        children: <Widget>[
          Swiper(
            itemCount: _guidePics.length,
            loop: false,
            pagination: SwiperPagination(),
            itemBuilder: (context, index) {
              return Image.asset(
                _guidePics[index],
                fit: BoxFit.cover,
                width: double.infinity,
                height: double.infinity,
              );
            },
            onIndexChanged: (index) {
              setState(() {
                _currentIndex = index;
              });
            },
          ),
          _currentIndex == _guidePics.length - 1
              ? Positioned(
                  bottom: 40,
                  child: RaisedButton(
                    color: CommonColors.primary,
                    onPressed: () {
                      _goHome();
                    },
                    child: Text(
                      "立即体验",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                )
              : Container(),
        ],
      ),
    );
  }
}
